package com.link.play.fit.ai.ui.guide.ac

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.gson.Gson
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.AcGuidePbBinding
import com.link.play.fit.ai.kv.AuthCache
import com.link.play.fit.ai.kv.AuthCache.isInitGuide
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.ui.guide.AccomplishFg
import com.link.play.fit.ai.ui.guide.AccountFg
import com.link.play.fit.ai.ui.guide.BasePageFragment
import com.link.play.fit.ai.ui.guide.BornFg
import com.link.play.fit.ai.ui.guide.CalAlFg
import com.link.play.fit.ai.ui.guide.ChooseWeightFg
import com.link.play.fit.ai.ui.guide.CrushGoalFg
import com.link.play.fit.ai.ui.guide.DietFragment
import com.link.play.fit.ai.ui.guide.EatMealsFg
import com.link.play.fit.ai.ui.guide.FastingGoalFg
import com.link.play.fit.ai.ui.guide.FastingTimeFg
import com.link.play.fit.ai.ui.guide.GenderFg
import com.link.play.fit.ai.ui.guide.GoalFg
import com.link.play.fit.ai.ui.guide.GuideViewModel
import com.link.play.fit.ai.ui.guide.HeightWeightFg
import com.link.play.fit.ai.ui.guide.PersonalTrainFg
import com.link.play.fit.ai.ui.guide.NotificationFg
import com.link.play.fit.ai.ui.guide.PlanReadyFg
import com.link.play.fit.ai.ui.guide.RateFg
import com.link.play.fit.ai.ui.guide.ReachGoalFg
import com.link.play.fit.ai.ui.guide.SettingEveryFg
import com.link.play.fit.ai.ui.guide.StopGoalFg
import com.link.play.fit.ai.ui.guide.ThankFg
import com.link.play.fit.ai.ui.guide.WeightControlMethodFg
import com.link.play.fit.ai.ui.guide.WeightEasyFg
import com.link.play.fit.ai.ui.guide.WithoutAppFg
import com.link.play.fit.ai.ui.guide.WorkoutsFg
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.vip.VipFreeAc
import com.link.play.fit.ai.ui.weightcontrol.IntermittentFastingFg
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import com.link.play.fit.ai.utils.HealthUtils.convertCmToFtIn
import com.link.play.fit.ai.utils.HealthUtils.convertKgToLbs
import com.link.play.fit.ai.utils.HealthUtils.covertFtInToCm
import com.link.play.fit.ai.utils.convertLbsToKg
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class GuidePbAc : BaseActivity<AcGuidePbBinding>(AcGuidePbBinding::inflate) {

    val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[GuideViewModel::class.java]
    }

    var currentIndex = 0
    private val rateFg by lazy {
        RateFg()
    }
    private val genderFg by lazy {
        GenderFg()
    }
    private val workoutsFg by lazy {
        WorkoutsFg()
    }

    //    private val calAppFg by lazy {
//        CalAppFg()
//    }
    private val calAlFg by lazy {
        CalAlFg()
    }
    private val personalTrainFg by lazy {
        PersonalTrainFg()
    }
    private val weightControlMethodFg by lazy {
        WeightControlMethodFg()
    }
    private val heightWeightFg by lazy {
        HeightWeightFg()
    }
    private val bornFg by lazy {
        BornFg()
    }
    private val goalFg by lazy {
        GoalFg()
    }
    private val chooseWeightFg by lazy {
        ChooseWeightFg()
    }
    private val weightEasyFg by lazy {
        WeightEasyFg()
    }
    private val reachGoalFg by lazy {
        ReachGoalFg()
    }
    private val withoutAppFg by lazy {
        WithoutAppFg()
    }
    private val stopGoalFg by lazy {
        StopGoalFg()
    }
    private val dietFragment by lazy {
        DietFragment()
    }
    private val accomplishFg by lazy {
        AccomplishFg()
    }
    private val crushGoalFg by lazy {
        CrushGoalFg()
    }
    private val fastingGoalFg by lazy {
        FastingGoalFg()
    }
    private val fastingTimeFg by lazy {
        FastingTimeFg()
    }
    private val eatMealsFg by lazy {
        EatMealsFg()
    }
    private val notificationFg by lazy {
        NotificationFg()
    }
    private val thankFg by lazy {
        ThankFg()
    }
    private val settingEveryFg by lazy {
        SettingEveryFg()
    }
    private val planReadyFg by lazy {
        PlanReadyFg()
    }
    private val accountFg by lazy {
        AccountFg()
    }
    private val intermittentFastingFg1 by lazy {
        IntermittentFastingFg().apply {
            this.page = 0
        }
    }
    private val intermittentFastingFg2 by lazy {
        IntermittentFastingFg().apply {
            this.page = 1
        }
    }
    private val intermittentFastingFg3 by lazy {
        IntermittentFastingFg().apply {
            this.page = 2
        }
    }

    private var isWeightControlGuide = RemoteConfig.isWeightControlGuide//是否减肥流程

    private var blackList: ArrayList<Int> = arrayListOf()
    private val fragments: MutableList<Fragment> by lazy {
        if (isWeightControlGuide) {
            mutableListOf(
                genderFg,
                workoutsFg,
                calAlFg,
                heightWeightFg,
                bornFg,
                goalFg,

                personalTrainFg,//个性化训练

                weightControlMethodFg,//减肥流程
                intermittentFastingFg1,//断食1
                intermittentFastingFg2,//断食2
                intermittentFastingFg3,//断食3

                chooseWeightFg,
                weightEasyFg,
                reachGoalFg,
                withoutAppFg,
                stopGoalFg,
                dietFragment,
                accomplishFg,
                crushGoalFg,

                fastingGoalFg,//减肥流程
                fastingTimeFg,//减肥流程

                eatMealsFg,
//                rateFg,
                notificationFg,
                thankFg,
                settingEveryFg,
                planReadyFg
            )
        } else {
            mutableListOf(
                genderFg,
                workoutsFg,
                calAlFg,
                heightWeightFg,
                bornFg,
                goalFg,
                chooseWeightFg,
                weightEasyFg,
                reachGoalFg,
                withoutAppFg,
                stopGoalFg,
                dietFragment,
                accomplishFg,
                crushGoalFg,
                eatMealsFg,
//                rateFg,
                notificationFg,
                thankFg,
                settingEveryFg,
                planReadyFg
            )
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isVip") {
            binding.viewPager2.setCurrentItem(accountFg.pageIndex, false)
        }
        if (event == "noVipCanIn") {
            blackList.add(planReadyFg.pageIndex)
            binding.viewPager2.setCurrentItem(accountFg.pageIndex, true)
        }
    }

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }
    }

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        EventBus.getDefault().register(this)

        fragments.forEachIndexed { index, fragment ->
            val pageFragment = (fragment as BasePageFragment<*>)
            pageFragment.pageIndex = index
            Log.e(TAG, "order $index ${pageFragment.TAG}")
        }

        binding.pb.max = fragments.size
        initViewPager2()
        binding.tvNext.setOnClickListener {

            if (BuildConfig.DEBUG) {
                val fragment = fragments[currentIndex] as BasePageFragment<*>
                Log.e(TAG, "tvNext currentIndex=$currentIndex ${fragment.TAG} ${fragment.pageIndex}")
            }
            //添加回退列表
            if (currentIndex != planReadyFg.pageIndex) {
                blackList.add(currentIndex)
            }

            val elseAction = {
                binding.viewPager2.setCurrentItem(currentIndex + 1, true)
            }
            val getStartAction = {
                saveUserGuide()
                goToAc(MainAc::class.java)
               finish()
            }

            //是否处于断食流程
            val isFastingFlow = isWeightControlGuide
                    && viewModel.userGuideState.value.goal == 2
                    && viewModel.userGuideState.value.needPersonalTrain == 1
                    && viewModel.userGuideState.value.weighControlMethod == 0

            //处于卡路里控制
            val isCalorieControlFlow = isWeightControlGuide
                    && viewModel.userGuideState.value.goal == 2
                    && viewModel.userGuideState.value.needPersonalTrain == 1
                    && viewModel.userGuideState.value.weighControlMethod == 1


            when (currentIndex) {

                heightWeightFg.pageIndex -> {
                    viewModel.userGuideState.update {
                        val new = it.copy(id = it.id + 1)

                        if (it.imperialMetric) {//公制
                            new.weightLbs = convertKgToLbs(it.weightKg)

                            val ftIn = convertCmToFtIn(it.heightCm.toDouble())
                            new.heightFt = ftIn.first
                            new.heightIn = ftIn.second
                        } else {
                            val kg = convertLbsToKg(it.weightLbs)
                            Log.e(TAG, "switchCompat kg=$kg")
                            new.weightKg = kg

                            val cm = covertFtInToCm(it.heightFt, it.heightIn)
                            new.heightCm = cm
                        }
                        new
                    }
                    binding.viewPager2.setCurrentItem(currentIndex + 1, true)
                }

                chooseWeightFg.pageIndex -> {

                    viewModel.userGuideState.update {
                        val new = it.copy(id = it.id + 1)

                        if (it.imperialMetric) {//公制
                            new.goal = if (it.weightKg < it.goalWeightKg) {
                                0
                            } else if (it.weightKg > it.goalWeightKg) {
                                2
                            } else {
                                1
                            }
                        } else {
                            new.goal = if (it.weightLbs < it.goalWeightLbs) {
                                0
                            } else if (it.weightLbs > it.goalWeightLbs) {
                                2
                            } else {
                                1
                            }
                        }

                        new
                    }

                    if (viewModel.userGuideState.value.goal == 1) {
                        binding.viewPager2.setCurrentItem(dietFragment.pageIndex, false)
                    } else {
                        binding.viewPager2.setCurrentItem(currentIndex + 1, true)
                    }
                }

                goalFg.pageIndex -> {

                    viewModel.userGuideState.update {
                        when (it.goal) {
                            0 -> {
                                it.goalWeightKg = it.weightKg + 10
                                it.goalWeightLbs = it.weightLbs + 10
                            }

                            1 -> {
                                it.goalWeightKg = it.weightKg
                                it.goalWeightLbs = it.weightLbs
                            }

                            2 -> {
                                it.goalWeightKg = it.weightKg - 10
                                it.goalWeightLbs = it.weightLbs - 10
                            }
                        }
                        it.copy(id = it.id + 1)
                    }

                    when {
                        isWeightControlGuide -> {
                            binding.viewPager2.setCurrentItem(personalTrainFg.pageIndex, true)
                        }

                        viewModel.userGuideState.value.goal == 1 -> {
                            binding.viewPager2.setCurrentItem(dietFragment.pageIndex, false)
                        }

                        else -> {
                            binding.viewPager2.setCurrentItem(chooseWeightFg.pageIndex, true)
                        }
                    }
                }

                personalTrainFg.pageIndex -> {

                    when {

                        isWeightControlGuide
                                && viewModel.userGuideState.value.goal == 2
                                && viewModel.userGuideState.value.needPersonalTrain == 1 -> {
                            binding.viewPager2.setCurrentItem(weightControlMethodFg.pageIndex, true)
                        }

                        viewModel.userGuideState.value.goal == 1 -> {
                            binding.viewPager2.setCurrentItem(dietFragment.pageIndex, false)
                        }

                        else -> {
                            binding.viewPager2.setCurrentItem(chooseWeightFg.pageIndex, false)
                        }
                    }
                }

                weightControlMethodFg.pageIndex -> {
                    when {
                        isFastingFlow -> {
                            binding.viewPager2.setCurrentItem(intermittentFastingFg1.pageIndex, true)
                        }

                        isCalorieControlFlow -> {
                            binding.viewPager2.setCurrentItem(chooseWeightFg.pageIndex, false)
                        }

                        else -> {
                            elseAction.invoke()
                        }
                    }
                }

                crushGoalFg.pageIndex -> {
                    when {
                        isFastingFlow -> {
                            binding.viewPager2.setCurrentItem(fastingGoalFg.pageIndex, false)
                        }

                        else -> {
                            binding.viewPager2.setCurrentItem(eatMealsFg.pageIndex, false)
                        }
                    }
                }

                planReadyFg.pageIndex -> {
                    if (isVip) {
                        getStartAction.invoke()
                    } else {
                        goToAc(VipFreeAc::class.java) {
                            putExtra("isGuide", true)
                        }
                        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left)
                    }
                }

                else -> {
                    elseAction.invoke()
                }
            }

        }

        onBackPressedDispatcher.addCallback {
            Log.e(TAG, "onBackPressedDispatcher currentIndex=$currentIndex")
            when {
                currentIndex == 0 -> {
                    if (AuthCache.tempUserGuide != null) {
                        blackList.add(0)
                        binding.viewPager2.setCurrentItem(planReadyFg.pageIndex, false)
                        viewModel.userGuideState.update { it.copy(dataReady = true) }
                    }
                }

                currentIndex == planReadyFg.pageIndex -> {
                    blackList.clear()
                    blackList.add(planReadyFg.pageIndex)
                    binding.viewPager2.setCurrentItem(0, false)
                    viewModel.userGuideState.update { it.copy(dataReady = false) }
                }

                else -> {
                    if (blackList.isNotEmpty()) {
                        val backIndex = blackList.last()
                        Log.e(TAG, "onBackPressedDispatcher backIndex=$backIndex")
                        blackList.removeLast()
                        val flag = currentIndex - backIndex == 1
                        binding.viewPager2.setCurrentItem(backIndex, flag)
                    }
                }
            }

        }

        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        /**
         * 当数据改变时切换按钮状态
         */
        lifecycleScope.launch {
            viewModel.userGuideState.collectLatest {
                changeBtnState(currentIndex, it)
            }
        }

        val bean = AuthCache.tempUserGuide
        Log.e(TAG, "bean=$bean")
        AuthCache.tempUserGuide?.let { temp ->
            binding.viewPager2.setCurrentItem(planReadyFg.pageIndex, false)
            val tempBean: UserGuide? = Gson().fromJson(temp, UserGuide::class.java)
            tempBean?.let { viewModel.userGuideState.update { tempBean } }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    /**
     * 切换按钮状态
     */
    private fun changeBtnState(position: Int, data: UserGuide) {

        var showNext = true
        when (position) {
            genderFg.pageIndex -> {
                binding.tvNext.isEnabled = data.gender != -1
            }

            workoutsFg.pageIndex -> {
                binding.tvNext.isEnabled = data.workouts != -1
            }

//            calAppFg.pageIndex -> {
//                binding.tvNext.isEnabled = data.calApp != -1
//            }
            personalTrainFg.pageIndex -> {
                binding.tvNext.isEnabled = data.needPersonalTrain != -1
            }

            weightControlMethodFg.pageIndex -> {
                binding.tvNext.isEnabled = data.weighControlMethod != -1
            }

            goalFg.pageIndex -> {
                binding.tvNext.isEnabled = data.goal != -1
            }

            stopGoalFg.pageIndex -> {
                binding.tvNext.isEnabled = data.stopGoal != -1
            }

            fastingGoalFg.pageIndex -> {
                binding.tvNext.isEnabled = data.fastingGoal != -1
            }

            fastingTimeFg.pageIndex -> {
                binding.tvNext.isEnabled = data.fastingStartTime != ""
            }

            dietFragment.pageIndex -> {
                binding.tvNext.isEnabled = data.diet != -1
            }

            accomplishFg.pageIndex -> {
                binding.tvNext.isEnabled = data.accomplish != -1
            }

            thankFg.pageIndex -> {
                binding.tvNext.text = getString(R.string.create_my_plan)
                showNext = false
            }

            settingEveryFg.pageIndex -> {
                binding.tvNext.visibility = View.INVISIBLE
            }

            planReadyFg.pageIndex -> {
                binding.tvNext.visibility = View.VISIBLE
                binding.tvNext.text = getString(R.string.let_s_get_started)
                binding.tvNext.isEnabled = true
                showNext = false
            }

            accountFg.pageIndex -> {
                binding.tvNext.visibility = View.GONE

            }

            else -> {
                binding.tvNext.visibility = View.VISIBLE
                binding.tvNext.isEnabled = true
            }
        }

        if (showNext) {
            binding.tvNext.text = resources.getString(R.string.next)
        }

    }

    private fun initViewPager2() {
        binding.viewPager2.run {
            isUserInputEnabled = false
            adapter = object : FragmentStateAdapter(this@GuidePbAc) {
                override fun getItemCount(): Int {
                    return fragments.size
                }

                override fun createFragment(position: Int): Fragment {
                    return fragments[position]
                }
            }
        }
        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
                currentIndex = position
                changeAcUI(position)
            }
        })
    }

    /**
     * 改变activity页面状态
     */
    private fun changeAcUI(position: Int) {

        binding.pb.progress = position + 1

        when (position) {
            0 -> {
                if (AuthCache.tempUserGuide == null) {
                    binding.clTop.visibility = View.INVISIBLE
                } else {
                    binding.clTop.visibility = View.VISIBLE
                }
            }

            settingEveryFg.pageIndex -> {
                binding.clTop.visibility = View.INVISIBLE
            }

            intermittentFastingFg1.pageIndex,
            intermittentFastingFg2.pageIndex,
            intermittentFastingFg3.pageIndex,
            -> {
                binding.pb.visibility = View.INVISIBLE
            }

            else -> {
                binding.pb.visibility = View.VISIBLE
                binding.clTop.visibility = View.VISIBLE
            }
        }


        changeBtnState(position, viewModel.userGuideState.value)
    }

    /**
     * 完成设置计划加载
     *
     */
    fun settingPlanFinish() {
        binding.viewPager2.setCurrentItem(planReadyFg.pageIndex, false)
        val data = viewModel.userGuideState.value
        Log.e("settingPlanFinish", "${data.bmr}")
        Log.e("settingPlanFinish", "${data.caloriesDaily}")
        Log.e("settingPlanFinish", "${data.carbsDaily}")
        viewModel.userGuideState.update {
            it.copy(id = it.id++)
        }
    }

    private fun saveUserGuide() {
        isInitGuide = true
        val userGuideState = viewModel.userGuideState.value
        userGuideState.haveWeighControlPlan = RemoteConfig.isWeightControlGuide && (userGuideState.needPersonalTrain == 1)
        //保存引导数据的信息
        CloudStore.set(CloudStore.DOC_USER_GUIDE, userGuideState)
        //保存当天的体重记录
        CloudStore.addToList(
            DOC_LOG_WEIGHT,
            DOC_LOG_WEIGHT,
            getDayOfMonth(),
            LogWeightBean(userGuideState.weightKg, userGuideState.weightLbs)
        )
    }


}